import * as THREE from 'three';

class TexturePlaneManager {
  constructor() {
    // 引用Three.js实例
    this.scene = null;
    this.camera = null;
    this.canvas = null;
    this.context = null;
    
    // 3D对象引用
    this.texture = null;
    this.material = null;
    this.geometry = null;
    this.plane = null;
    
    // 字幕状态
    this.isVisible = false;
    this.currentText = '';
    
    // 位置配置 - 调整位置使字幕更靠近用户且居中
    this.positionOffset = new THREE.Vector3(0, -0.2, -1.0); // 相机坐标系下的偏移
    
    console.log('TexturePlaneManager initialized');
  }
  
  /**
   * 设置场景和相机引用
   * @param {THREE.Scene} scene - Three.js场景
   * @param {THREE.Camera} camera - Three.js相机
   */
  setSceneAndCamera(scene, camera) {
    this.scene = scene;
    this.camera = camera;
    console.log('TexturePlaneManager scene and camera set');
  }
  
  /**
   * 设置Canvas引用
   * @param {HTMLCanvasElement} canvas - Canvas元素
   */
  setCanvas(canvas) {
    this.canvas = canvas;
    this.context = canvas.getContext('2d');
    this._initTextureAndPlane();
  }
  
  /**
   * 初始化纹理和平面
   * @private
   */
  _initTextureAndPlane() {
    if (!this.canvas || !this.scene) {
      console.warn('Cannot initialize texture and plane: missing canvas or scene');
      return;
    }
    
    // 清理现有对象
    this._dispose();
    
    // 生成纹理
    this.texture = new THREE.CanvasTexture(this.canvas);
    this.texture.minFilter = THREE.LinearFilter;
    this.texture.magFilter = THREE.LinearFilter;
    this.texture.generateMipmaps = false;
    
    // 创建材质 - 优化XR兼容性
    this.material = new THREE.MeshBasicMaterial({
      map: this.texture,
      transparent: true,
      opacity: 0.9,
      side: THREE.DoubleSide, // 双面显示确保在XR中可见
      depthTest: false,      // 禁用深度测试，确保字幕始终可见
      depthWrite: false      // 禁用深度写入，避免影响其他物体
    });
    
    // 创建几何体 - 保持与Canvas相同的宽高比
    const aspectRatio = this.canvas.width / this.canvas.height;
    const planeWidth = 1.0; // 适当减小宽度以配合字体大小的调整
    const planeHeight = planeWidth / aspectRatio;
    
    this.geometry = new THREE.PlaneGeometry(planeWidth, planeHeight);
    
    // 创建网格
    this.plane = new THREE.Mesh(this.geometry, this.material);
    
    // 设置渲染属性 - 确保字幕在XR中显示在最前面
    this.plane.renderOrder = 1000;
    this.plane.material.depthTest = false;
    this.plane.material.depthWrite = false;
    
    // 初始状态设置为隐藏
    this.plane.visible = false;
    
    // 添加到场景
    this.scene.add(this.plane);
    
    console.log('Texture and plane initialized with dimensions:', planeWidth, 'x', planeHeight);
  }
  
  /**
   * 更新纹理
   */
  updateTexture() {
    if (this.texture) {
      this.texture.needsUpdate = true;
      this.showSubtitle();
    }
  }
  
  /**
   * 显示字幕
   */
  showSubtitle() {
    if (this.plane) {
      this.plane.visible = true;
      this.isVisible = true;
    }
  }
  
  /**
   * 隐藏字幕
   */
  hideSubtitle() {
    if (this.plane) {
      this.plane.visible = false;
      this.isVisible = false;
    }
  }
  
  /**
   * 更新头部锁定位置
   * 在每帧渲染时调用
   */
  updatePosition() {
    if (!this.camera || !this.plane) return;
    
    // 计算字幕在世界坐标系中的位置
    const worldPosition = new THREE.Vector3();
    
    // 从相机视角应用偏移量
    worldPosition.copy(this.camera.position);
    
    // 计算相机前方的方向
    const direction = new THREE.Vector3(0, 0, -1);
    direction.applyQuaternion(this.camera.quaternion);
    
    // 计算偏移向量（在相机局部坐标系中）
    const offset = new THREE.Vector3();
    offset.copy(this.positionOffset);
    
    // 将偏移向量从相机局部坐标系转换到世界坐标系
    const cameraMatrix = new THREE.Matrix4();
    cameraMatrix.extractRotation(this.camera.matrixWorld);
    offset.applyMatrix4(cameraMatrix);
    
    // 应用偏移量到相机位置
    worldPosition.add(offset);
    
    // 设置字幕平面的位置
    this.plane.position.copy(worldPosition);
    
    // 确保字幕始终面向摄像机
    this.plane.lookAt(this.camera.position);
    
    // 确保渲染属性正确设置
    if (this.plane && this.plane.material) {
      this.plane.renderOrder = 1000;
      this.plane.material.depthTest = false;
      this.plane.material.depthWrite = false;
    }
    
    // 调整旋转以保持文本正确朝向（不翻转）
    this.plane.rotateX(Math.PI); // 调整平面朝向，确保文本正向
  }
  
  /**
   * 设置位置偏移
   * @param {number} x - X轴偏移
   * @param {number} y - Y轴偏移
   * @param {number} z - Z轴偏移
   */
  setPositionOffset(x, y, z) {
    this.positionOffset.set(x, y, z);
    console.log('Subtitle position offset updated:', x, y, z);
  }
  
  /**
   * 调整平面大小
   * @param {number} scale - 缩放因子
   */
  scalePlane(scale) {
    if (this.plane) {
      this.plane.scale.set(scale, scale, 1);
      console.log('Subtitle plane scaled by:', scale);
    }
  }
  
  /**
     * 更新字幕文本
     * @param {string} text - 字幕文本
     */
    updateSubtitle(text) {
      console.log('🔄 TexturePlaneManager.updateSubtitle:', text);
      
      if (!this.plane) {
        console.error('❌ 字幕平面未创建');
        return;
      }
      
      if (!this.context) {
        console.error('❌ Canvas context 不可用');
        return;
      }
      
      // 保存当前文本
      this.currentText = text;
      
      // 渲染文本
      this.renderText(text);
      
      // 关键：确保平面可见
      this.plane.visible = true;
      
      // 强制渲染更新
      if (this.texture) {
        this.texture.needsUpdate = true;
      }
      
      console.log('✅ 字幕平面更新完成，可见性:', this.plane.visible);
    }
  
  /**
   * 获取平面引用
   * @returns {THREE.Mesh|null} 平面网格或null
   */
  getPlane() {
    return this.plane;
  }
  
  /**
   * 获取纹理引用
   * @returns {THREE.Texture|null} 纹理或null
   */
  getTexture() {
    return this.texture;
  }
  
  /**
   * 获取Canvas上下文
   * @returns {CanvasRenderingContext2D|null} Canvas上下文或null
   */
  getContext() {
    return this.context;
  }
  
  /**
   * 获取Canvas元素
   * @returns {HTMLCanvasElement|null} Canvas元素或null
   */
  getCanvas() {
    return this.canvas;
  }
  
  /**
   * 设置平面可见性
   * @param {boolean} visible - 是否可见
   */
  setPlaneVisible(visible) {
    if (this.plane) {
      this.plane.visible = visible;
    }
  }
  
  /**
   * 检查平面是否可见
   * @returns {boolean} 平面可见性
   */
  isPlaneVisible() {
    return this.plane ? this.plane.visible : false;
  }

  /**
   * 增强渲染方法
   * @param {string} text - 要渲染的文本
   */
  renderText(text) {
    if (!this.context || !this.canvas) {
      console.error('Cannot render text: missing canvas or context');
      return;
    }
    
    const ctx = this.context;
    const canvas = this.canvas;
    
    // 清除画布
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    
    if (!text || text.trim() === '') {
      return; // 空文本不渲染
    }
    
    // 更醒目的文本样式
    ctx.font = 'bold 36px "PingFang SC", "Microsoft YaHei", sans-serif';
    ctx.fillStyle = '#FFFFFF';
    ctx.strokeStyle = '#000000';
    ctx.lineWidth = 6;
    ctx.textAlign = 'center';
    ctx.textBaseline = 'middle';
    
    // 添加阴影增强可读性
    ctx.shadowColor = 'rgba(0, 0, 0, 0.8)';
    ctx.shadowBlur = 8;
    ctx.shadowOffsetX = 2;
    ctx.shadowOffsetY = 2;
    
    // 绘制描边
    ctx.strokeText(text, canvas.width / 2, canvas.height / 2);
    
    // 绘制填充
    ctx.fillText(text, canvas.width / 2, canvas.height / 2);
    
    // 重置阴影
    ctx.shadowColor = 'transparent';
    ctx.shadowBlur = 0;
    ctx.shadowOffsetX = 0;
    ctx.shadowOffsetY = 0;
    
    console.log('Text rendered:', text);
  }
  
  /**
   * 清理资源
   * @private
   */
  _dispose() {
    if (this.texture) {
      this.texture.dispose();
      this.texture = null;
    }
    
    if (this.material) {
      this.material.dispose();
      this.material = null;
    }
    
    if (this.geometry) {
      this.geometry.dispose();
      this.geometry = null;
    }
    
    if (this.plane && this.scene) {
      this.scene.remove(this.plane);
      this.plane = null;
    }
  }
  
  /**
   * 完全销毁管理器
   */
  dispose() {
    this._dispose();
    this.scene = null;
    this.camera = null;
    this.canvas = null;
    this.context = null;
    console.log('TexturePlaneManager disposed');
  }
}

// 导出单例实例
const texturePlaneManager = new TexturePlaneManager();
export default texturePlaneManager;